<template>
    <!-- @focus="focusEvent()" -->
    <el-select clearable @change="changeEvent" ref="elSelectRef" v-model="currentItem"
        :model-value="modelValue" @update:model-value="$emit('update:modelValue', $event)"
        :loading="loading" placeholder="请选择">
        <el-option v-for="(item, index) in options" :key="item.value + index" :label="item.label" :value="item.value"
            style="display: none" />

        <!-- <div> <el-input style="padding:2px 5px;" @keyup="keyupEvent" size="mini" v-model="searchkey"
                placeholder="请输入关键字 回车 ENTER"></el-input></div> -->

        <vxe-table size="mini"
             border
             @keyup="keyupEvent"
             height="180px"
             @cell-click="cellClickEvent"
             :data="gridOptions.data">

            <vxe-column header-align="center" :min-width="item.minWidth" :key="index + item.field" v-for="(item, index) in gridOptions.columns" :field="item.field" :title="item.title"></vxe-column>
            </vxe-table>
            <el-pagination v-show="showPager" background size="small" :current-page="tablePage.currentPage"
                :page-size="tablePage.pageSize" @current-change="handlePageChange" layout="prev, pager, next"
                :total="tablePage.total">
            </el-pagination>
    </el-select>
</template>
<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
// import { useRoute } from 'vue-router'
import { useSearchItemComposable } from './minxin'

const cacheDataObj = {}

// Props
const props = defineProps({
    modelValue: {
        type: [String, Number],
        default: ''
    },
    fieldName: {
        type: String,
        default: ""
    },
    field: {
        type: String,
        default: ''
    },
    row: {
        type: Object,
        default() {
            return {}
        }
    }
    // 查询配置
    // configOptions: {
    //     type: Object,
    //     default() {
    //         return {}
    //     }
    // }
})

// Emits
const emit = defineEmits(['update:modelValue', 'changeEvent'])

// Composables
// const route = useRoute()
let fullURL = window.location.href;
const instance = getCurrentInstance()
const { init, changeEvent: baseChangeEvent, getDBDataByActionName } = useSearchItemComposable()

// Reactive data
const currentItem = ref(null)
const configFormItem = ref(null)
const showPager = ref(false)
const loading = ref(false)
const displayField = ref([]) // 需要显示的字段
const searchkey = ref("")
const tablePage = ref({
    total: 0,
    currentPage: 1,
    pageSize: 10
})
const options = ref([])
const selectConfig = ref({
    key: "",
    text: ""
})
const gridOptions = ref({
    columns: [],
    data: []
})

// Refs
const elSelectRef = ref(null)

// Computed
const configOptions = computed(() => {
    let _configOptions = {}
    try {
        _configOptions = props.row.controlOptions
    } catch (error) {
        _configOptions = {}
    }
    return _configOptions
})

// Lifecycle
onMounted(() => {
    init()
    focusEvent()
    setTimeout(() => {
        if (!!props.modelValue) {
            currentItem.value = props.modelValue
        }
    }, 300)
})
// Methods
// 设置缓存
const setCacheData = (dataList) => {
    cacheDataObj[fullURL + props.field] = dataList
}

// 读取缓存
const getCacheData = () => {
    // debugger
    let dataList = []
    try {
        dataList = cacheDataObj[fullURL + props.field]
    } catch (error) {
        dataList = []
    }
    return dataList
}

// 单击当前行
const cellClickEvent = (tableInfo) => {
    // debugger
    currentItem.value = tableInfo.row[selectConfig.value.key]
    props.row[props.fieldName] = currentItem.value
    elSelectRef.value?.blur();
}

// 表格查询框 回车键
const keyupEvent = ($event) => {
    if ($event.keyCode === 13) {
        loadSelectOptions()
    }
}
const focusEvent = (params) => {
    //debugger
    //  CIS_PAGE: "N",// 是否分页
    //   CPAGE_SIZE: 10,// 分页数
    // 初始化 下拉配置信息
    if (options.value.length == 0) {
        if (configOptions.value) {
            configFormItem.value = configOptions.value
            if (configFormItem.value.hasOwnProperty('CDATAS') && !!configFormItem.value.CDATAS) {
                getSelectKeyText(configFormItem.value.CDATAS)
                tablePage.value.pageSize = Number(configFormItem.value.CPAGE_SIZE)
                showPager.value = (configFormItem.value.CIS_PAGE == 'Y' ? true : false)
            }
        }
        loadSelectOptions()
    }
}
// 获取配置的KEY & TEXT
const getSelectKeyText = (dataList) => {
    //debugger
    //dataList = orderBy(dataList, ["fieldOrder"], ["asc"]); // 升序排序
    displayField.value = [] // 重置需要显示的字段
    gridOptions.value.columns = []
    if (dataList && dataList.length > 0) {
        dataList.forEach(item => {
            if (!!item.isSelectTextField) {
                selectConfig.value.text = item.field
            }
            if (!!item.isSelectKeyField) {
                selectConfig.value.key = item.field
            }
           // item.iisShowList
            if (!!item.iisShowList) {
                let newItem = {
                    field: item.field,
                    headerAlign: 'center',
                    minWidth: Number(item.width),
                    title: !!item.title ? item.title : item.field
                }
                displayField.value.push(newItem)
                gridOptions.value.columns.push(newItem)
            }
        })
    } else {
        selectConfig.value = {
            key: "",
            text: ""
        }
    }
}
// 设置下拉初始化功能
const loadSelectOptions = async () => {
    //debugger
    loading.value = true
    let _dataList = []
    // ===读取缓存数据列表====
    let cecheDataList = getCacheData()
    if(cecheDataList && cecheDataList.length > 0){
        _dataList = cecheDataList
        // ===读取缓存数据列表====
    } else {
        _dataList = await getDBDataByActionName(configFormItem.value);
        setCacheData(_dataList)
    }

    if(_dataList && _dataList.length > 0){
        options.value = formatDatas(_dataList)
        gridOptions.value.data = _dataList
    } else {
        options.value = [{ value: "", label: "请选择" }]
    }

    loading.value = false
    setTimeout(() => {
        loading.value = false
    }, 10000)
}

// 格式化返回数据
const formatDatas = (dataList) => {
    let optionsList = [{ value: "", label: "请选择" }]
    if (dataList && dataList.length > 0) {
        dataList.forEach(oldItem => {
            if (!!oldItem[selectConfig.value.text]) {
                let newItem = {
                    value: oldItem[selectConfig.value.key],
                    label: oldItem[selectConfig.value.text]
                }
                optionsList.push(newItem)
            }
        })
    }
    return optionsList
}

const handlePageChange = (val) => {
    tablePage.value.currentPage = val
    loadSelectOptions()
}

// 选择改变触发事件
const changeEvent = (val) => {
    emit('update:modelValue', val)
    baseChangeEvent(val)
    let params = {
        value: val,
        type: 'change'
    }
    emit("changeEvent", params)
}
</script>


<style lang="scss" scoped></style>